package net.xdclass.demo1;


import com.zaxxer.hikari.HikariDataSource; 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源ben
 */
@MapperScan(basePackages = "net.xdclass.demo1.mapper")
@Configuration
public class DynamicDataSourceConfiguration {

    /**
     * 武汉数据源
     * @return
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.wh")
    public DataSource wuhan(){
        return new HikariDataSource();
    }

    /**
     * 恩施数据源
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.es")
    public DataSource enshi(){
        return new HikariDataSource();
    }

    /**
     * 核心动态数据源配置
     * @return
     */
    @Bean
    public DataSource dynamicDataSource(){
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
        Map<Object,Object> dataSourceMap = new HashMap<>(2);
        //设置默认数据源
        dataSource.setDefaultTargetDataSource(wuhan());
        //配置数据源
        dataSourceMap.put(CityEnum.wuhan.getCity(),wuhan());
        dataSourceMap.put(CityEnum.enshi.getCity(),enshi());
        dataSource.setTargetDataSources(dataSourceMap);
        return dataSource;
    }

    /**
     * sql工厂
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        //此处设置为了解决找不到mapper文件的问题
        sqlSessionFactoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * sql模板
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory());
    }

    /**
     * 事务管理
     * @return
     */
    @Bean
    public PlatformTransactionManager platformTransactionManager(){
        return new DataSourceTransactionManager(dynamicDataSource());
    }
}

